<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-01-11 18:43:59
 * @LastEditors: Andy
 * @LastEditTime: 2023-02-15 15:17:27
-->
<template>
  <x-dialog :title="title" :show.sync="visible" :before-close="handleClose" width="40%">
    <el-form
      ref="template"
      :model="templateDetail"
      :rules="rules"
      class="demo-form-inline"
      label-position="top"
      label-width="auto"
    >
      <el-row :gutter="36">
        <el-col :span="24">
          <el-form-item :label="$t('resourceAdmin.template.templateName')" prop="templateName" clearable>
            <el-input
              v-model="templateDetail.templateName"
              :placeholder="$t('resourceAdmin.template.modulePlaceholder')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('resourceAdmin.template.templateCode')" prop="templateCode">
            <el-input
              v-model="templateDetail.templateCode"
              :placeholder="$t('resourceAdmin.template.titlePlaceholder')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('resourceAdmin.template.filePath')" prop="filePath">
            <x-upload
              ref="fileUpload"
              :edit-flag="true"
              :limit="1"
              :fileSize="30"
              :span="24"
              :isFileRemark="false"
              :old-file-list="filesList"
              :file-type="['jpg', 'jpeg', 'png', 'ppt', 'pptx', 'pdf', 'xls', 'xlsx']"
              :tips="'支持上传PPT/PDF/EXCEL/PNG/JPG形式文件,附件大小不超过30MB.'"
            >
            </x-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('resourceAdmin.template.state')" prop="state">
            <x-radio-group :list-data="dictOptions['system.state']" v-model="templateDetail.state"></x-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('resourceAdmin.template.remark')" prop="remark">
            <el-input
              v-model="templateDetail.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 8 }"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          btnLoading = true
          handleSubmit()
        "
        :loading="btnLoading"
      >
        {{ $t('common.save') }}
      </el-button>
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle } from '@package/utils'
  import { apiPutEditTemplate, apiPostAddTemplate, apiGetTemplateInfo } from '../api/template.js'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    props: {
      dictOptions: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        visible: false,
        title: '',
        templateDetail: {
          state: '1',
          templateName: '',
          templateCode: '',
          filePath: '',
          fileName: '',
          remark: ''
        },
        filesList: [],
        rules: {
          templateName: [
            { required: true, message: this.$t('resourceAdmin.template.templateNamePlaceholder'), trigger: 'blur' }
          ],
          templateCode: [
            { required: true, message: this.$t('resourceAdmin.template.titlePlaceholder'), trigger: 'blur' }
          ],
          state: [{ required: true, message: this.$t('resourceAdmin.template.statePlaceholder'), trigger: 'blur' }],
          filePath: [{ required: true, message: this.$t('resourceAdmin.template.filePlaceholder'), trigger: 'change' }]
        },
        dictKeys: ['system.state'],
        btnLoading: false
      }
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.templateDetail = JSON.parse(JSON.stringify(info))
          this.title = this.$t('common.edit')
          apiGetTemplateInfo(info.id).then(({ data }) => {
            this.templateDetail = Object.assign(this.templateDetail, cloneDeep(data))
            this.templateDetail.state += ''
            this.filesList = [{ fileName: this.templateDetail.fileName, filePath: this.templateDetail.filePath }]
          })
          return
        }
        this.title = this.$t('common.add')
      },
      handleClose() {
        this.$refs.template.resetFields()
        this.templateDetail = omit(this.templateDetail, 'id')
        this.templateDetail.fileName = ''
        this.templateDetail.filePath = ''
        this.filesList = []
        this.btnLoading = false
        this.visible = false
      },
      //  提交
      handleSubmit: throttle(function () {
        this.btnLoading = true
        const { fileList } = this.$refs.fileUpload
        this.templateDetail.fileName = fileList.length ? fileList[0].fileName || fileList[0].response.data.fileName : ''
        this.templateDetail.filePath = fileList.length ? fileList[0].filePath || fileList[0].response.data.filePath : ''
        this.$refs.template.validate(async (valid) => {
          if (valid) {
            const param = {
              ...this.templateDetail
            }
            try {
              const { code, msg } = this.templateDetail.id
                ? await apiPutEditTemplate(param)
                : await apiPostAddTemplate(param)
              this.btnLoading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleClose()
                this.$emit('handleSuccess')
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.btnLoading = false
            }
          } else {
            this.btnLoading = false
            return false
          }
        })
      }, 1000)
    }
  }
</script>
